package fr.ajicommerce;

import java.util.Collection;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import fr.ajicommerce.core.dto.UtilisateurBackOfficeDTO;
import fr.ajicommerce.core.service.facade.Facade;
import fr.ajicommerce.core.service.interfaces.UtilisateurBackOfficeService;

@Component("monServiceAuthentification")
public class MonServiceAuthentification implements UserDetailsService{

	@Autowired
	Facade facade;
	
	@Override
	public UserDetails loadUserByUsername(String arg0)
			throws UsernameNotFoundException {
		//Retrieve the user from wherever you store it, e.g. a database 
		
		UtilisateurBackOfficeService service = facade.getUtilisateurBackOfficeService();
		
		UtilisateurBackOfficeDTO uDTO =  service.findUtilisateurBackOfficeByLogin(arg0);
	    if (uDTO == null) {
	    	
	        throw new UsernameNotFoundException("toto invalid login.");
	    }
	    
	    Collection<? extends GrantedAuthority> authorities = AuthorityUtils.createAuthorityList(uDTO.getMyTypeDUtilisateur().toString());
	    
	    return new User(uDTO.getLogin(),uDTO.getMotDePasse(), authorities);
	}

}
